/*
 * Copyright (c) 2025 粤港澳大湾区（广东）国创中心
 *
 * This file is a part of NctiCAEPre.
 *
 * NctiCAEPre is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 *
 */

#include "OptionsDlg.h"

#include <fstream>

#include <QStyledItemDelegate>
#include <QPainter>

#include <QListView>
#include <QComboBox>
#include <QRadioButton>
#include <QCheckBox>
#include <QListWidget>
#include <QHeaderView>
#include <QStringListModel>
#include <QDir>
#include <QCoreApplication>
#include <QTimer>
#include <QFileDialog>
#include <QMessageBox>
#include <QStackedWidget>
#include <QButtonGroup>
#include <QFormLayout>
#include <QGroupBox>

#include <QDebug>

#include "NctiPluginsManager.h"
#include "NctiQTPubFun.h"

#include "SelectColorWidget.h"
#include "CustomDelegate.h"
#include "ModelColorPreviewWidget.h"

namespace NCTI {

class LineTypeDelegate : public QStyledItemDelegate
{
public:
    LineTypeDelegate(QObject* parent = nullptr)
        : QStyledItemDelegate(parent)
    {
    }

    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override
    {
        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);

        painter->save();

        // 根据索引判断线条类型并绘制
        QString text       = index.data(Qt::DisplayRole).toString();
        int lineTypeWidth  = 60; // 线条预览的宽度
        int lineTypeHeight = 2;  // 线条预览的高度
        int padding        = 5;  // 间距

        // 先绘制线条
        int lineX = opt.rect.x() + padding;
        int lineY = opt.rect.y() + (opt.rect.height() - lineTypeHeight) / 2;
        if (text == "实线") {
            painter->drawLine(lineX, lineY, lineX + lineTypeWidth, lineY);
        }
        else if (text == "点线") {
            for (int i = 0; i <= lineTypeWidth; i += 4) {
                painter->drawPoint(lineX + i, lineY);
            }
        }
        else if (text == "点划线") {
            for (int i = 0; i <= lineTypeWidth; i += 12) {
                painter->drawLine(lineX + i, lineY, lineX + i + 4, lineY);
                painter->drawPoint(lineX + i + 8, lineY);
            }
        }
        else if (text == "中心线") {
            for (int i = 0; i <= lineTypeWidth; i += 16) {
                painter->drawLine(lineX + i, lineY, lineX + i + 6, lineY);
                painter->drawLine(lineX + i + 10, lineY, lineX + i + 12, lineY);
            }
        }
        else if (text == "虚线") {
            for (int i = 0; i <= lineTypeWidth; i += 8) {
                painter->drawLine(lineX + i, lineY, lineX + i + 4, lineY);
            }
        }
        else if (text == "双点线") {
            for (int i = 0; i <= lineTypeWidth; i += 16) {
                painter->drawLine(lineX + i, lineY, lineX + i + 4, lineY);
                painter->drawPoint(lineX + i + 8, lineY);
                painter->drawPoint(lineX + i + 12, lineY);
            }
        }
        else if (text == "三点线") {
            for (int i = 0; i < lineTypeWidth; i += 20) {
                painter->drawLine(lineX + i, lineY, lineX + i + 4, lineY);
                painter->drawPoint(lineX + i + 8, lineY);
                painter->drawPoint(lineX + i + 12, lineY);
                painter->drawPoint(lineX + i + 16, lineY);
            }
        }
        // 再绘制文本，文本起始位置在线条右侧
        int textX = lineX + lineTypeWidth + padding;
        painter->drawText(textX, opt.rect.y() + (opt.rect.height() + painter->fontMetrics().ascent()) / 2, text);

        painter->restore();
    }
};

static std::string LineTypeToString(int lineType)
{
    switch (lineType) {
        case 0: return "SolidLine";
        case 1: return "DotLine";
        case 2: return "DotDashLine";
        case 3: return "CenterLine";
        case 4: return "DashLine";
        case 5: return "DotDotLine";
        case 6: return "DotDotDotLine";
        default: break;
    }
    return "SolidLine";
}

// clang-format off
static int LineTypeToIndex(const std::string& lineType)
{
    if (lineType == "SolidLine")    { return 0; }
    if (lineType == "DotLine")      { return 1; }
    if (lineType == "DotDashLine")  { return 2; }
    if (lineType == "CenterLine")   { return 3; }
    if (lineType == "DashLine")     { return 4; }
    if (lineType == "DotDotLine")   { return 5; }
    if (lineType == "DotDotDotLine"){ return 6; }
    return 0;
}
// clang-format on

static bool checkPluginExists(QTreeWidget* treeWidget, const QString& target)
{
    for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
        QTreeWidgetItem* parent = treeWidget->topLevelItem(i);
        for (int j = 0; j < parent->childCount(); ++j) {
            QTreeWidgetItem* child = parent->child(j);
            if (child->text(0).compare(target, Qt::CaseInsensitive) == 0) {
                return true;
            }
        }
    }
    return false;
}

static std::string toStdString(const QString& value)
{
    QByteArray ba = value.toUtf8();
    return std::string(ba.constData());
}

static std::string getStringColor(QPushButton* button)
{
    if (button) {
        return toStdString(button->property("buttonColor").value<QColor>().name());
    }
    return "";
}

OptionsDlg::OptionsDlg(QWidget* parent)
    : PopupBaseDialog(parent)
{
    setupUI();
    initConnects();
    initAppConfig();
    this->installEventFilter(this);
    modelColorPreviewWidget->installEventFilter(this);
}

OptionsDlg::~OptionsDlg()
{
}

void OptionsDlg::setupUI()
{
    initWidgets();

    setTitle("选项卡");
    this->layout()->setContentsMargins(0, 0, 0, 0);

    auto widget = new QFrame(this);
    widget->setObjectName("newOptionsDlg");

    QVBoxLayout* vBoxLayout = new QVBoxLayout(widget);
    vBoxLayout->setContentsMargins(0, 0, 0, 0);

    QHBoxLayout* hBoxLayout = new QHBoxLayout;
    hBoxLayout->setContentsMargins(0, 0, 0, 0);
    vBoxLayout->addSpacing(2);
    vBoxLayout->addLayout(hBoxLayout);

    QFrame* itemFrame = new QFrame;
    itemFrame->setObjectName("optionsItem_Frame");
    itemFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    itemFrame->setMinimumSize(QSize(150, 0));
    itemFrame->setMaximumSize(QSize(150, 16777215));
    hBoxLayout->addWidget(itemFrame);

    QVBoxLayout* itemLayout = new QVBoxLayout(itemFrame);
    itemLayout->setContentsMargins(6, 0, 6, 0);
    itemLayout->addWidget(itemListView);
    hBoxLayout->addSpacing(10);

    QFrame* functionFrame = new QFrame;
    hBoxLayout->addWidget(functionFrame);

    QVBoxLayout* functionLayout = new QVBoxLayout(functionFrame);
    functionLayout->setContentsMargins(0, 0, 0, 0);

    //展示不同的界面
    QStackedWidget* stackedWidget = new QStackedWidget(functionFrame);
    functionLayout->addWidget(stackedWidget);
    functionLayout->addSpacing(2);

    //恢复和保存的组件
    QWidget* buttonWidget = new QWidget;
    functionLayout->addWidget(buttonWidget);
    buttonWidget->setFixedHeight(30);
    functionLayout->addWidget(buttonWidget);

    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);
    buttonLayout->setContentsMargins(0, 0, 0, 0);
    buttonLayout->addStretch();
    buttonLayout->addWidget(defaultBtn);
    buttonLayout->addWidget(saveBtn);

    stackedWidget->addWidget(CreateThemeColorWidget());             //主题颜色
    stackedWidget->addWidget(CreateMultilingualWidget());           //多语言
    stackedWidget->addWidget(CreateCADEnvironmentSettingsWidget()); //环境设置
    stackedWidget->addWidget(CreatePathSettingsWidget());           //路径设置
    stackedWidget->addWidget(CreateLoadingPluginsWidget());         //加载插件
    stackedWidget->addWidget(CreateWindowWidget());                 //窗口，脚本编辑器和控制台
    stackedWidget->addWidget(CreateBackupsWidget());                //备份

    connect(itemListView->selectionModel(),
            &QItemSelectionModel::currentRowChanged,
            [this, stackedWidget](const QModelIndex& current) {
                if (current.isValid()) {
                    stackedWidget->setCurrentIndex(current.row());
                }
                onHideSelectColorWidget();
            });

    setWidget(widget);
}

void OptionsDlg::CreateItemListView()
{
    itemListView = new QListView(this);
    itemListView->setObjectName("optionsItem_ListView");
    itemListView->setEditTriggers(QAbstractItemView::NoEditTriggers); //设置不可编辑

    QStringListModel* model = new QStringListModel;
    model->setStringList({ "主题颜色", "多语言", "环境设置", "路径设置", "加载插件", "窗口", "备份" });
    itemListView->setModel(model);

    CustomDelegate* delegate = new CustomDelegate(itemListView);
    itemListView->setItemDelegate(delegate);
    itemListView->setCurrentIndex(model->index(0));
}

void OptionsDlg::CreateDefaultBtn()
{
    // 恢复默认按钮
    defaultBtn = new QPushButton();
    defaultBtn->setObjectName("pushButton_restore_default");
    defaultBtn->setText("恢复默认");
    defaultBtn->setFixedSize(90, 30);
}

void OptionsDlg::CreateSaveBtn()
{
    // 保存按钮
    saveBtn = new QPushButton();
    saveBtn->setObjectName("pushButton_save");
    saveBtn->setText("保存");
    saveBtn->setFixedSize(90, 30);
}

QPushButton* OptionsDlg::CreateColorBtn(const QString& objName)
{
    QPushButton* button = new QPushButton;
    button->setObjectName(objName);
    button->setFixedSize(23, 23);
    return button;
}

void OptionsDlg::initWidgets()
{
    CreateItemListView();
    CreateDefaultBtn();
    CreateSaveBtn();

    QString styleSheet = QString(R"(
            background-color: rgb(229, 232, 241);
            border-radius: 5px;
            color: rgb(0, 0, 0);
        )");
    floatingLabel = new QLabel(this);
    floatingLabel->setStyleSheet(styleSheet);
    floatingLabel->setAlignment(Qt::AlignCenter);
    floatingLabel->hide();

    // 颜色选择窗口
    colorWidget = new SelectColorWidget(this);
    colorWidget->setFixedSize(254, 120);
    colorWidget->hide();
    colorWidgetVisible = false;

    backgroundGradientColorLabel = new QLineEdit;
    backgroundGradientColorLabel->setObjectName("backgroundGradientColor_LineEdit");
    backgroundGradientColorLabel->setReadOnly(true);
    backgroundGradientColorLabel->setFixedSize(70, 23);

    topColorBtn                     = CreateColorBtn("topColor_Button");
    bottomColorBtn                  = CreateColorBtn("bottomColor_Button");
    faceColorBtn                    = CreateColorBtn("faceColor_Button");
    edgeColorBtn                    = CreateColorBtn("edgeColor_Button");
    vertexColorBtn                  = CreateColorBtn("vertexColor_Button");
    highLightColorBtn               = CreateColorBtn("highlightColor_Button");
    lineSegmentColorBtn             = CreateColorBtn("lineSegmentsColor_Button");
    dimensionLineColorBtn           = CreateColorBtn("dimensionLinesColor_Button");
    gridLineColorBtn                = CreateColorBtn("gridLineColor_Button");
    backFaceColorSettingBtn         = CreateColorBtn("backFaceColorSetting_Btn");
    highlightContourColorSettingBtn = CreateColorBtn("highlightContourColorSetting_Btn");
}

void OptionsDlg::initColorConnections()
{
    // 背景渐变色
    connect(topColorBtn, &QPushButton::clicked, [this]() { onShowColorWidgetBelowButton(topColorBtn); });
    connect(bottomColorBtn, &QPushButton::clicked, [this]() { onShowColorWidgetBelowButton(bottomColorBtn); });

    // 模型
    connect(faceColorBtn, &QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonModel(faceColorBtn); });
    connect(edgeColorBtn, &QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonModel(edgeColorBtn); });
    connect(vertexColorBtn, &QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonModel(vertexColorBtn); });
    connect(highLightColorBtn,&QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonModel(highLightColorBtn); });

    // 草图
    connect(lineSegmentColorBtn,
        &QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonSketch(lineSegmentColorBtn); });
    connect(dimensionLineColorBtn,
        &QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonSketch(dimensionLineColorBtn); });
    connect(gridLineColorBtn,
        &QPushButton::clicked, [this]() { onShowColorWidgetBelowButtonSketch(gridLineColorBtn); });

    // 背面颜色
    connect(backFaceColorSettingBtn, &QPushButton::clicked, this, [this]() {
        onShowColorWidgetBelowButton_Render(backFaceColorSettingBtn);
        });

    // 轮廓颜色
    connect(highlightContourColorSettingBtn, &QPushButton::clicked, this, [this]() {
        onShowColorWidgetBelowButton_Render(highlightContourColorSettingBtn);
        });

    //设置选择的颜色
    connect(colorWidget->getSelectColorLabel(),
        &ColorLabel::colorPicked, [this](const QColor& color) { setButtonColor(color); });

    //对于用户输入的颜色值进行设置
    connect(colorWidget, &SelectColorWidget::inputColor, [this](const QColor& color) { onUpdateColor(color); });
}

void OptionsDlg::initPathConnections()
{
    //路径设置，增加，删除，浏览
    connect(addTestCasePathBtn, &QPushButton::clicked, [this] { onAddTestCasePathClicked(); });
    connect(deleteTestCasePathBtn, &QPushButton::clicked, [this] { onDeleteTestCasePathClicked(); });
    connect(pythonScriptPathButton, &QPushButton::clicked, [this] { onPythonScriptPathClicked(); });
    connect(pythonPathButton, &QPushButton::clicked, [this] { onPythonPathClicked(); });
}

void OptionsDlg::initPluginConnections()
{
    //加载插件
    connect(addLoadingPluginBtn, &QPushButton::clicked, [this] { onAddLoadingPluginsClicked(); });
    connect(deleteLoadingPluginBtn, &QPushButton::clicked, [this] { onDeleteLoadingPluginsClicked(); });
}

void OptionsDlg::initBackupConnections()
{
    //备份开启关闭，备份路径设置
    connect(openBackupsButton, &QPushButton::clicked, [this] { onOpenBackups(); });
    connect(closeBackupsButton, &QPushButton::clicked, [this] { onCloseBackups(); });
    connect(backupPathBtn, &QPushButton::clicked, [this] { onBackupPath(); });
}

void OptionsDlg::initConnects()
{
    initColorConnections();

    // 渲染设置
    connect(modelFaceCheckBox, &QCheckBox::toggled, [this] { onUpdateBackColor(); });
    connect(highlightContourCheckBox, &QCheckBox::toggled, [this] { onUpdateContourColor(); });

    // 对象显示模式
    connect(faceBtn, &QPushButton::toggled, [this] { onFaceButtonToggled(); });
    connect(edgeBtn, &QPushButton::toggled, [this] { onEdgeButtonToggled(); });
    connect(vertexBtn, &QPushButton::toggled, [this] { onVertexButtonToggled(); });

    // 操作轴
    connect(displayOperatingAxiseBtn, &QRadioButton::clicked, [this] { onHideSelectColorWidget(); });
    connect(hideOperatingAxiseBtn, &QRadioButton::clicked, [this] { onHideSelectColorWidget(); });

    initPathConnections();
    
    initPluginConnections();

    initBackupConnections();

    connect(defaultBtn, &QPushButton::clicked, [this] { onRestoreDefault(); });
    connect(saveBtn, &QPushButton::clicked, [this] { onSaveConfig(); });
}

void OptionsDlg::initAppConfig(bool useDefault)
{
    QFileInfo fileInfo(QCoreApplication::applicationFilePath());
    QString configFile     = QString::fromUtf8(NctiPluginsManager::instance()->GetConfigurationFile());
    QString configFilePath = QString("%1/%2").arg(fileInfo.absolutePath(), configFile);
    if (!QFile::exists(configFilePath)) {
        // 配置文件不存在, 生成默认配置
        writeJsonFile(configFilePath, AppConfig());
    }
    
    if (!useDefault) {
        try {
            std::ifstream file(configFilePath.toUtf8());
            if (file.is_open()) {
                json j = json::parse(file);
                mAppConfig = j.get<AppConfig>();
            }
        }
        catch (const json::parse_error& e) {
            qWarning() << "json parse error: " << e.what();
        }
        catch (const std::exception& e) {
            qWarning() << "std::exception: " << e.what();
        }
    }

    if (mAppConfig.Windows.AutoSaveFolder.empty()) {
        QDir tempDir(QDir::tempPath());
        if (tempDir.mkpath("NCTI")) {
            mAppConfig.Windows.AutoSaveFolder = toStdString(tempDir.filePath("NCTI"));
        }
    }

    //主题颜色
    themeColorComboBox->setCurrentIndex(mAppConfig.Windows.ThemeColor == "dark" ? 0 : 1);

    //语言
    languageComboBox->setCurrentIndex(mAppConfig.Windows.Language == "chinese" ? 0 : 1);

    //面、线、点颜色
    QString faceColor   = QString::fromStdString(mAppConfig.Windows.FaceColor.c_str());
    QString edgeColor   = QString::fromStdString(mAppConfig.Windows.EdgeColor.c_str());
    QString vertexColor = QString::fromStdString(mAppConfig.Windows.VertexColor.c_str());
    setColorButtonStyleSheet(faceColorBtn, faceColor);     //面
    setColorButtonStyleSheet(edgeColorBtn, edgeColor);     //线
    setColorButtonStyleSheet(vertexColorBtn, vertexColor); //点
    QString highlightColor = QString::fromStdString(mAppConfig.Windows.HighlightColor.c_str());
    setColorButtonStyleSheet(highLightColorBtn, QColor(highlightColor));                            //高亮

    //模型颜色
    modelColorPreviewWidget->set_faceColor(faceColor);
    modelColorPreviewWidget->set_lineColor(edgeColor);
    modelColorPreviewWidget->set_pointColor(vertexColor);
    modelColorPreviewWidget->set_selectColor(highlightColor);

    //背面颜色
    lineTypeComBox->setCurrentIndex(mAppConfig.Windows.LineType);
    lineWidthLineEdit->setText(QString::number(mAppConfig.Windows.LineWidth, 'g', 6));
    modelFaceCheckBox->setChecked(mAppConfig.Windows.ShowBackColor);
    QColor backColor(mAppConfig.Windows.BackColor.c_str());
    setColorButtonStyleSheet(backFaceColorSettingBtn, backColor);
    onUpdateBackColor();

    // 轮廓颜色
    highlightContourCheckBox->setChecked(mAppConfig.Windows.ShowContour);
    QColor contourColor(mAppConfig.Windows.ContourColor.c_str());
    setColorButtonStyleSheet(highlightContourColorSettingBtn, contourColor);
    onUpdateContourColor();

    //草图绘制
    setColorButtonStyleSheet(lineSegmentColorBtn, QColor(mAppConfig.Windows.LineSegmentColor.c_str()));     //线段
    setColorButtonStyleSheet(dimensionLineColorBtn, QColor(mAppConfig.Windows.DimensionLineColor.c_str())); //尺寸线
    setColorButtonStyleSheet(gridLineColorBtn, QColor(mAppConfig.Windows.GridLineColor.c_str()));           //网格线



    // 渲染设置

    //背景渐变色
    QString topColorValue = QString::fromStdString(mAppConfig.Renderer.BackgroundColor.at(0));
    QString bottomColorValue = QString::fromStdString(mAppConfig.Renderer.BackgroundColor.at(1));
    setColorButtonStyleSheet(topColorBtn, QColor(topColorValue));
    setColorButtonStyleSheet(bottomColorBtn, QColor(bottomColorValue));
    updateBackgroundColor();

    //显示模式，面、线、点
    faceBtn->setChecked(mAppConfig.Renderer.ObjectDisplayMode[0]);
    edgeBtn->setChecked(mAppConfig.Renderer.ObjectDisplayMode[1]);
    vertexBtn->setChecked(mAppConfig.Renderer.ObjectDisplayMode[2]);

    //操作轴
    if (mAppConfig.Renderer.OperatingAxis) {
        displayOperatingAxiseBtn->setChecked(true);
    }
    else {
        hideOperatingAxiseBtn->setChecked(true);
    }

    // 帧率显示
    if (mAppConfig.Renderer.OpenRenderDisplayTime) {
        displayFrameRateButton->setChecked(true);
    }
    else {
        hideFrameRateButton->setChecked(true);
    }

    // 是否实时高亮
    if (mAppConfig.Renderer.RenderPreHighlight) {
        highlightBtn->setChecked(true);
    }
    else {
        hideHighlightBtn->setChecked(true);
    }
    
    // 是否框选所有
    if (mAppConfig.Renderer.RenderBoxSelctAll) {
        selectAllBtn->setChecked(true);
    }
    else {
        hideSelectAllBtn->setChecked(true);
    }

    //测试用例
    QStringList importPathList;
    importPathList.reserve(mAppConfig.Windows.ImportPath.size());
    for (const auto& path : mAppConfig.Windows.ImportPath) {
        importPathList.append(QString::fromStdString(path));
    }
    testCasePathListWidget->clear();
    testCasePathListWidget->addItems(importPathList);

    //python脚本路径
    pythonScriptPathLineEdit->setText(QString::fromUtf8(mAppConfig.Windows.FunctionPath.c_str()));

    //python路径
    pythonPathLineEdit->setText(QString::fromUtf8(mAppConfig.Windows.PythonPath.c_str()));

    //加载插件
    initPlugins(mAppConfig);

    //控制台
    if (mAppConfig.Windows.Console) {
        displayConsoleButton->setChecked(true);
    }
    else {
        hideConsoleButton->setChecked(true);
    }

    //脚本编辑器
    if (mAppConfig.Windows.ScriptEditor) {
        displayScriptEditorButton->setChecked(true);
    }
    else {
        hideScriptEditorButton->setChecked(true);
    }

    //备份开启或关闭
    if (mAppConfig.Windows.AutoSaveValid) {
        openBackupsButton->setChecked(true);
        onOpenBackups();
    }
    else {
        closeBackupsButton->setChecked(true);
        onCloseBackups();
    }

    //备份间隔时间
    int autoSaveTime = mAppConfig.Windows.AutoSaveTime / 60;
    timeLineEdit->setText(QString::number(autoSaveTime));

    //备份路径
    QString backupPathValue = QString::fromUtf8(mAppConfig.Windows.AutoSaveFolder.c_str());
    backupPathLineEdit->setText(backupPathValue);
}

void OptionsDlg::initPlugins(const AppConfig& config)
{
    treeWidget->clear();
    for (const auto& item : config.Windows.LoadDLL) {
        std::visit(
            [this](const auto& value) {
                using T = std::decay_t<decltype(value)>;

                if constexpr (std::is_same_v<T, std::string>) {
                    auto parentItem = new QTreeWidgetItem(treeWidget);
                    parentItem->setText(0, "");
                    auto childItem = new QTreeWidgetItem(parentItem);
                    childItem->setText(0, QString::fromStdString(value));
                }
                else if constexpr (std::is_same_v<T, std::vector<std::string>>) {
                    if (value.size() >= 2) {
                        QTreeWidgetItem* parentItem = nullptr;
                        QString parentName          = QString::fromUtf8(value[0].c_str());
                        for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
                            if (treeWidget->topLevelItem(i)->text(0) == parentName) {
                                parentItem = treeWidget->topLevelItem(i);
                                break;
                            }
                        }
                        if (!parentItem) {
                            parentItem = new QTreeWidgetItem(treeWidget);
                            parentItem->setText(0, parentName);
                        }
                        for (size_t n = 1; n < value.size(); n++) {
                            QString childName = QString::fromUtf8(value[n].c_str());
                            auto childItem    = new QTreeWidgetItem(parentItem);
                            childItem->setText(0, childName);
                        }
                    }
                }
            },
            item);
    }
    treeWidget->expandAll();
}

void OptionsDlg::getPluginsData(AppConfig& config) const
{
    config.Windows.LoadDLL.clear();

    for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
        QTreeWidgetItem* topLevelItem = treeWidget->topLevelItem(i);

        if (topLevelItem->text(0).isEmpty()) {
            // 处理单个 DLL 项（没有父节点的项）
            for (int j = 0; j < topLevelItem->childCount(); ++j) {
                QTreeWidgetItem* childItem = topLevelItem->child(j);
                if (!childItem->text(0).isEmpty()) {
                    config.Windows.LoadDLL.emplace_back(toStdString(childItem->text(0)));
                }
            }
        }
        else {
            // 处理分组 DLL 项（有父节点的项）
            if (topLevelItem->childCount() > 0) {
                std::vector<std::string> group;
                group.push_back(toStdString(topLevelItem->text(0)));

                // 添加所有子节点
                for (int j = 0; j < topLevelItem->childCount(); ++j) {
                    QTreeWidgetItem* childItem = topLevelItem->child(j);
                    if (!childItem->text(0).isEmpty()) {
                        group.push_back(toStdString(childItem->text(0)));
                    }
                }
                config.Windows.LoadDLL.emplace_back(std::move(group));
            }
            else {
                // 如果父节点没有子节点，将其作为单个 DLL 处理
                config.Windows.LoadDLL.emplace_back(toStdString(topLevelItem->text(0)));
            }
        }
    }
}

void OptionsDlg::setColorButtonStyleSheet(QPushButton* button, const QColor& color)
{
    QString styleSheet = QString(R"(
            QPushButton {
            border: 1px solid #8f8f91;
            border-radius: 4px;
            background: %1;
        }
        )").arg(color.name());
    button->setProperty("buttonColor", color);
    button->setStyleSheet(styleSheet);
}

void OptionsDlg::updateBackgroundColor()
{
    QColor topColor    = topColorBtn->property("buttonColor").value<QColor>();
    QColor bottomColor = bottomColorBtn->property("buttonColor").value<QColor>();

    //渐变方向
    // x1: 0,   y1: 0,   x2: 1,   y2: 1   是从左上角到右下角，
    // x1: 0,   y1: 0.5, x2: 1,   y2: 0.5 是从左到右，
    // x1: 0.5, y1: 0,   x2: 0.5, y2: 1   是从上到下。
    QString styleSheet_backgroundColor = QString(R"(
        QLineEdit {
            border: 1px solid #8f8f91;
            border-radius: 4px;
            padding: 5px;
            background: qlineargradient(x1: 0.5, y1: 0, x2: 0.5, y2: 1,
                stop: 0 %1,
                stop: 1 %2);
        })").arg(topColor.name()).arg(bottomColor.name());
    backgroundGradientColorLabel->setStyleSheet(styleSheet_backgroundColor);
}

// clang-format off
void OptionsDlg::setPreviewModelWidgetColor(QPushButton* button, const QColor& color)
{
    if (button == edgeColorBtn)           { modelColorPreviewWidget->set_lineColor(color);  }
    else if (button == vertexColorBtn)    { modelColorPreviewWidget->set_pointColor(color); }
    else if (button == faceColorBtn)      { modelColorPreviewWidget->set_faceColor(color);  }
    else if (button == highLightColorBtn) { modelColorPreviewWidget->set_selectColor(color);}
}
// clang-format on

bool OptionsDlg::writeJsonFile(const QString& jsonPath, const AppConfig& appConfig)
{
    std::wstring savePath = jsonPath.toStdWString();
    try {
        json j = appConfig;
        std::ofstream file(savePath);
        file << j.dump(4);
        return true;
    }
    catch (const std::exception& e) {
        qWarning() << "Error: " << e.what();
    }
    return false;
}

void OptionsDlg::updateAppConfigJson()
{
    QFileInfo fileInfo(QCoreApplication::applicationFilePath());
    QString configFile     = QString::fromUtf8(NctiPluginsManager::instance()->GetConfigurationFile());
    QString configFilePath = QString("%1/%2").arg(fileInfo.absolutePath(), configFile);

    bool ok{ false };
    double dLineWidth = lineWidthLineEdit->text().toDouble(&ok);
    dLineWidth = ok ? dLineWidth : 1.0;

    mAppConfig.Windows.ThemeColor         = (themeColorComboBox->currentIndex() == 0) ? "dark" : "light";
    mAppConfig.Windows.Language           = (languageComboBox->currentIndex() == 0) ? "chinese" : "english";
    mAppConfig.Windows.FaceColor          = getStringColor(faceColorBtn);          //面
    mAppConfig.Windows.EdgeColor          = getStringColor(edgeColorBtn);          //线
    mAppConfig.Windows.VertexColor        = getStringColor(vertexColorBtn);        //点
    mAppConfig.Windows.HighlightColor     = getStringColor(highLightColorBtn);     //高亮
    mAppConfig.Windows.LineSegmentColor   = getStringColor(lineSegmentColorBtn);   //线段
    mAppConfig.Windows.DimensionLineColor = getStringColor(dimensionLineColorBtn); //尺寸线
    mAppConfig.Windows.GridLineColor      = getStringColor(gridLineColorBtn);      //网格线

    mAppConfig.Windows.LineType = lineTypeComBox->currentIndex();
    mAppConfig.Windows.LineWidth = dLineWidth;
    mAppConfig.Windows.ShowBackColor = modelFaceCheckBox->isChecked();
    mAppConfig.Windows.BackColor = getStringColor(backFaceColorSettingBtn);
    mAppConfig.Windows.ShowContour = highlightContourCheckBox->isChecked();
    mAppConfig.Windows.ContourColor = getStringColor(highlightContourColorSettingBtn);

    //测试用例路径
    mAppConfig.Windows.ImportPath.clear();
    for (int i = 0; i < testCasePathListWidget->count(); ++i) {
        QListWidgetItem* item = testCasePathListWidget->item(i);
        if (item) {
            mAppConfig.Windows.ImportPath.push_back(toStdString(item->text()));
        }
    }

    mAppConfig.Windows.FunctionPath  = toStdString(pythonScriptPathLineEdit->text());
    mAppConfig.Windows.PythonPath    = toStdString(pythonPathLineEdit->text());
    mAppConfig.Windows.Console       = displayConsoleButton->isChecked();
    mAppConfig.Windows.ScriptEditor  = displayScriptEditorButton->isChecked();
    mAppConfig.Windows.AutoSaveValid = openBackupsButton->isChecked();

    //自动备份时间
    int autoSaveTime              = timeLineEdit->text().toInt(&ok, 10);
    autoSaveTime                  = ok ? autoSaveTime * 60 : 300;
    mAppConfig.Windows.AutoSaveTime   = autoSaveTime;
    mAppConfig.Windows.AutoSaveFolder = toStdString(backupPathLineEdit->text());

    //获取插件
    getPluginsData(mAppConfig);

    //渲染配置
    mAppConfig.Renderer.BackgroundColor = { getStringColor(topColorBtn), getStringColor(bottomColorBtn) };
    mAppConfig.Renderer.ObjectDisplayMode = displayMode;                           //显示模式
    mAppConfig.Renderer.OperatingAxis = displayOperatingAxiseBtn->isChecked(); //操作轴
    mAppConfig.Renderer.OpenRenderDisplayTime = displayFrameRateButton->isChecked();
    mAppConfig.Renderer.RenderPreHighlight    = highlightBtn->isChecked();
    mAppConfig.Renderer.RenderBoxSelctAll     = selectAllBtn->isChecked();

    bool result_ok = writeJsonFile(configFilePath, mAppConfig);
    if (result_ok) {
        NctiQTPubFun::LoadingSystemParams();
        qDebug() << "JSON file updated successfully.";
    }
    else {
        qWarning() << "Failed to update JSON file.";
    }
}

void OptionsDlg::updateSelectColorWidget(const QColor& color)
{
    if (!colorWidget) {  return; }
    double r_top = static_cast<double>(color.red()) / 255.0;
    double g_top = static_cast<double>(color.green()) / 255.0;
    double b_top = static_cast<double>(color.blue()) / 255.0;

    colorWidget->getRedColorProgressBar()->setValue((int)(r_top * 1000));
    colorWidget->getGreenColorProgressBar()->setValue((int)(g_top * 1000));
    colorWidget->getBuleColorProgressBar()->setValue((int)(b_top * 1000));

    QString str_r = QString::number(r_top, 'f', 3);
    QString str_g = QString::number(g_top, 'f', 3);
    QString str_b = QString::number(b_top, 'f', 3);

    colorWidget->getRedColorProportionNum()->setText(str_r);
    colorWidget->getGreenColorProportionNum()->setText(str_g);
    colorWidget->getBuleColorProportionNum()->setText(str_b);
    colorWidget->getColorName()->setText(color.name().toUpper());
    colorWidget->updatePaint(color);
}

void OptionsDlg::updateDisplayModeIcon()
{
    QPixmap checkMode_pixmap(":/Option/checked.png");
    QPixmap uncheckMode_pixmap(":/Option/unchecked.png");
    checkMode_pixmap   = checkMode_pixmap.scaled(QSize(18, 18), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    uncheckMode_pixmap = uncheckMode_pixmap.scaled(QSize(18, 18), Qt::KeepAspectRatio, Qt::SmoothTransformation);

    faceIconLabel->setPixmap(displayMode[0] ? checkMode_pixmap : uncheckMode_pixmap);
    edgeIconLabel->setPixmap(displayMode[1] ? checkMode_pixmap : uncheckMode_pixmap);
    vertexIconLabel->setPixmap(displayMode[2] ? checkMode_pixmap : uncheckMode_pixmap);
}

void OptionsDlg::deleteItemRecursive(QTreeWidgetItem* item)
{
    if (!item) { return; }

    // 递归删除所有子节点
    for (int i = 0; i < item->childCount(); ++i) {
        deleteItemRecursive(item->child(i));
    }

    // 删除当前节点
    QTreeWidgetItem* parent = item->parent();
    if (parent) {
        parent->removeChild(item);
        if (parent->text(0).isEmpty()) {
            deleteItemRecursive(parent);
        }
        else if (parent->childCount() == 0) {
            parent->setText(0, "");
            deleteItemRecursive(parent);
        }
    }
    else {
        treeWidget->takeTopLevelItem(treeWidget->indexOfTopLevelItem(item));
    }
}

void OptionsDlg::showFloatingLabel()
{
    QPoint center = this->rect().center() - floatingLabel->rect().center();
    floatingLabel->move(center);
    floatingLabel->show();
    QTimer::singleShot(2000, this, &OptionsDlg::onFloatingLabel);
}

void OptionsDlg::showSelectColorWidget(const QColor& color, const QPoint& pos)
{
    updateSelectColorWidget(color);
    colorWidget->move(pos);
    colorWidget->show();
    colorWidgetVisible = true;
}

QTreeWidgetItem* OptionsDlg::addPluginInApplicationDir(const QString& appDir, const QString& pluginName)
{
    QTreeWidgetItem* parentItem = nullptr;
    
    QStringList parts = pluginName.split('_');
    if (parts.size() < 2) {
        return nullptr;
    }
    QString target = parts[1]; // 提取文件名中的特定部分，依赖项

    // 遍历文件所在的目录,不分大小写进行对比
    QDir dir{appDir};
    QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
    bool found = false;
    Q_FOREACH (const QFileInfo& entry, entries) {
        if (entry.isDir() && QString::compare(entry.fileName(), target, Qt::CaseInsensitive) == 0) {
            bool pluginExists = false;
            for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
                QTreeWidgetItem* pParent = treeWidget->topLevelItem(i);
                if (QString::compare(pParent->text(0), target, Qt::CaseInsensitive) == 0) {
                    parentItem   = pParent;
                    pluginExists = true;
                    break;
                }
                if (pluginExists) {
                    break;
                }
            }

            if (!pluginExists) {
                parentItem = new QTreeWidgetItem(treeWidget);
                parentItem->setText(0, entry.fileName());
            }
            found = true;
        }
    }
    if (!found) {
        parentItem = new QTreeWidgetItem(treeWidget);
        parentItem->setText(0, "");
    }
    return parentItem;
}

QTreeWidgetItem* OptionsDlg::addPluginInOutsideDir(const QString& pluginName)
{
    for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) {
        QTreeWidgetItem* item = treeWidget->topLevelItem(i);
        if (item->text(0).compare(pluginName, Qt::CaseInsensitive) == 0) {
            return item; // found and return
        }
    }
    // not found
    QTreeWidgetItem* parentItem = new QTreeWidgetItem(treeWidget);
    parentItem->setText(0, pluginName);
    return parentItem;
}

void OptionsDlg::onAddPlugin(const QString pluginPath, const QString plugin)
{
    QStringList parentNames = pluginPath.split(';');
    QStringList pluginNames = plugin.split(';');
    if (parentNames.size() != pluginNames.size()) {
        return;
    }
    QFileInfo fileInfo(QCoreApplication::applicationFilePath());
    QString applicationDir = fileInfo.absolutePath();
    for (int i = 0; i < parentNames.size(); ++i) {
        if (checkPluginExists(treeWidget, pluginNames[i])) {
            QMessageBox::information(this, "提示", QString("插件%1已存在").arg(pluginNames[i]));
            continue;
        }
        QTreeWidgetItem* parentItem = nullptr;
        if (applicationDir == parentNames[i]) {
            //应用程序目录中的插件
            parentItem = addPluginInApplicationDir(applicationDir, pluginNames[i]);
        }
        else {
            parentItem = addPluginInOutsideDir(pluginNames[i]);
        }
        if (parentItem) {
            QTreeWidgetItem* childItem = new QTreeWidgetItem(parentItem);
            childItem->setText(0, pluginNames[i]);
        }
    }
    treeWidget->expandAll();
}

void OptionsDlg::onRestoreDefault()
{
    onHideSelectColorWidget();
    initAppConfig(true);
    saveBtn->click(); //保存默认的设置到应用
    floatingLabel->setText("已恢复默认！");
    showFloatingLabel();
}

void OptionsDlg::onSaveConfig()
{
    onHideSelectColorWidget();
    floatingLabel->setText("已保存！");
    showFloatingLabel();
    updateAppConfigJson();
    Q_EMIT this->savePushButtonClicked();
}

void OptionsDlg::onFaceButtonToggled()
{
    onHideSelectColorWidget();
    displayMode[0] = faceBtn->isChecked();
    updateDisplayModeIcon();
}

void OptionsDlg::onEdgeButtonToggled()
{
    onHideSelectColorWidget();
    displayMode[1] = edgeBtn->isChecked();
    updateDisplayModeIcon();
}

void OptionsDlg::onVertexButtonToggled()
{
    onHideSelectColorWidget();
    displayMode[2] = vertexBtn->isChecked();
    updateDisplayModeIcon();
}

void OptionsDlg::onHideSelectColorWidget()
{
    colorWidget->hide();
    colorWidgetVisible = false;
}

void OptionsDlg::setButtonColor(const QColor& color)
{
    setColorButtonStyleSheet(currentActiveBtn, color);
    updateSelectColorWidget(color);

    if (currentActiveBtn == topColorBtn || currentActiveBtn == bottomColorBtn) {
        updateBackgroundColor();
    }
    else {
        setPreviewModelWidgetColor(currentActiveBtn, color);
    }
}

void OptionsDlg::onDeleteTestCasePathClicked()
{
    QListWidgetItem* selectedItem = testCasePathListWidget->currentItem();
    if (selectedItem) {
        int row = testCasePathListWidget->row(selectedItem); // 获取选中项目的行索引
        delete testCasePathListWidget->takeItem(row);
    }
    else {
        QMessageBox::information(this, "No Selection", "No item selected.");
    }
}

void OptionsDlg::onAddTestCasePathClicked()
{
    QString dirPath = QFileDialog::getExistingDirectory(
        this, "选择文件夹", "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if (dirPath.isEmpty()) {
        return;
    }

    bool exists = false;
    for (int i = 0; i < testCasePathListWidget->count(); ++i) {
        if (testCasePathListWidget->item(i)->text() == dirPath) {
            exists = true;
            break;
        }
    }

    if (!exists) {
        QListWidgetItem* newItem = new QListWidgetItem(dirPath);
        testCasePathListWidget->addItem(newItem);
    }
    else {
        QMessageBox::information(this, "Folder Already Exists", "The selected folder is already in the list.");
    }
}

void OptionsDlg::onPythonScriptPathClicked()
{
    selectDir(pythonScriptPathLineEdit);
}

void OptionsDlg::onPythonPathClicked()
{
    selectDir(pythonPathLineEdit);
}

void OptionsDlg::onBackupPath()
{
    selectDir(backupPathLineEdit);
}

void OptionsDlg::selectDir(QLineEdit* lineEdit)
{
    QString dirPath = QFileDialog::getExistingDirectory(
        this, "选择文件夹", "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if (!dirPath.isEmpty()) {
        lineEdit->setText(dirPath);
    }
}

void OptionsDlg::onDeleteLoadingPluginsClicked()
{
    QTreeWidgetItem* current_item = treeWidget->currentItem();
    if (!current_item) {
        return;
    }

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "提示", "确定删除？", QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        deleteItemRecursive(current_item);
    }
}

void OptionsDlg::onOpenBackups()
{
    timeLineEdit->setEnabled(true);
    backupPathLineEdit->setEnabled(true);
    backupPathBtn->setEnabled(true);
}

void OptionsDlg::onCloseBackups()
{
    timeLineEdit->setEnabled(false);
    backupPathLineEdit->setEnabled(false);
    backupPathBtn->setEnabled(false);
}

void OptionsDlg::onUpdateColor(const QColor& color)
{
    setButtonColor(color);
    updateSelectColorWidget(color);
}

void OptionsDlg::onUpdateBackColor()
{
    bool showBackColor = modelFaceCheckBox->isChecked();
    if (showBackColor) {
        backFaceColorSettingBtn->setEnabled(true);
    }
    else {
        backFaceColorSettingBtn->setEnabled(false);
    }
}

void OptionsDlg::onUpdateContourColor()
{
    bool showContourColor = highlightContourCheckBox->isChecked();
    if (showContourColor) {
        highlightContourColorSettingBtn->setEnabled(true);
    }
    else {
        highlightContourColorSettingBtn->setEnabled(false);
    }
}

void OptionsDlg::onShowColorWidgetBelowButton(QPushButton* button)
{
    QPoint buttonParentPos = button->mapToParent(QPoint(0, button->height()));
    int x                  = buttonParentPos.x() + 180;
    int y                  = buttonParentPos.y() + 75;

    QColor color = button->property("buttonColor").value<QColor>();
    showSelectColorWidget(color, QPoint{x, y});
    currentActiveBtn = button;
}

void OptionsDlg::onShowColorWidgetBelowButtonModel(QPushButton* button)
{
    QPoint buttonParentPos = button->mapToParent(QPoint(0, button->height()));
    int offsetX            = buttonParentPos.x() + 105;
    int offsetY            = buttonParentPos.y() + 115;

    QRect dlgGeometry = this->geometry();
    if (offsetX + colorWidget->width() > dlgGeometry.width()) {
        offsetX = dlgGeometry.width() - colorWidget->width();
    }

    QColor color = button->property("buttonColor").value<QColor>();
    showSelectColorWidget(color, QPoint{offsetX, offsetY});
    currentActiveBtn = button;
}

void OptionsDlg::onShowColorWidgetBelowButtonSketch(QPushButton* button)
{
    QPoint buttonParentPos = button->mapToParent(QPoint(0, button->height()));
    int offsetX            = buttonParentPos.x() + 63;
    int offsetY            = buttonParentPos.y() + 313;

    QRect dlgGeometry = this->geometry();
    if (offsetX + colorWidget->width() > dlgGeometry.width()) {
        offsetX = dlgGeometry.width() - colorWidget->width();
    }

    QColor color = button->property("buttonColor").value<QColor>();
    showSelectColorWidget(color, QPoint{offsetX, offsetY});
    currentActiveBtn = button;
}

void OptionsDlg::onShowColorWidgetBelowButton_Render(QPushButton* button)
{
    QPoint buttonParentPos = button->mapToParent(QPoint(0, button->height()));
    int offsetX            = buttonParentPos.x() + 165;
    int offsetY            = buttonParentPos.y() + 270;

    QRect dlgGeometry = this->geometry();
    if (offsetX + colorWidget->width() > dlgGeometry.width()) {
        offsetX = dlgGeometry.width() - colorWidget->width();
    }

    QColor color = button->property("buttonColor").value<QColor>();
    showSelectColorWidget(color, QPoint{offsetX, offsetY});
    currentActiveBtn = button;
}

void OptionsDlg::onAddLoadingPluginsClicked()
{
    addDLLWidget = new AddLoadingDLLWidget(this);
    addDLLWidget->setObjectName("addDLL_Widget");

    connect(addDLLWidget, &AddLoadingDLLWidget::selectPluginConfirmed,
            [this](const QString pluginPath, const QString plugin) { 
            onAddPlugin(pluginPath, plugin); 
        });
}

void OptionsDlg::setObjectDisplayMode(bool face, bool edge, bool vertex)
{
    displayMode = {face, edge, vertex};
}

void OptionsDlg::setConsoleState(bool consoleState)
{
    if (consoleState) {
        displayConsoleButton->setChecked(true);
    }
    else {
        hideConsoleButton->setChecked(true);
    }
}

void OptionsDlg::setScriptEditorState(bool scriptEditorState)
{
    if (scriptEditorState) {
        displayScriptEditorButton->setChecked(true);
    }
    else {
        hideScriptEditorButton->setChecked(true);
    }
}

void OptionsDlg::onFloatingLabel()
{
    floatingLabel->clear();
    floatingLabel->hide();
}

QWidget* OptionsDlg::CreateThemeColorWidget11()
{
    QWidget* widget         = new QWidget;
    QGridLayout* gridLayout = new QGridLayout(widget);
    gridLayout->setVerticalSpacing(21);

    QLabel* themeColorLabel = new QLabel(tr("主题颜色"), widget);
    themeColorLabel->setObjectName("theme_Color_Label");

    QLabel* selectThemeColorLabel = new QLabel(tr("选择主题："), widget);
    selectThemeColorLabel->setObjectName("select_Theme_Label");
    selectThemeColorLabel->resize(100, 30);

    themeColorComboBox = new QComboBox;
    themeColorComboBox->setObjectName("select_Theme_ComboBox");
    themeColorComboBox->addItem(tr("深色"));
    themeColorComboBox->addItem(tr("浅色"));
    themeColorComboBox->setView(new QListView);

    QSpacerItem* horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QSpacerItem* verticalSpacer   = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);

    gridLayout->addWidget(themeColorLabel, 0, 0);
    gridLayout->addWidget(selectThemeColorLabel, 1, 0);
    gridLayout->addWidget(themeColorComboBox, 1, 1);
    gridLayout->addItem(horizontalSpacer, 1, 2, 1, 1);
    gridLayout->addItem(verticalSpacer, 2, 0, 1, 1);

    return widget;
}

QWidget* OptionsDlg::CreateThemeColorWidget()
{
    QWidget* widget         = new QWidget;
    QFormLayout* formLayout = new QFormLayout(widget);
    formLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
    formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);

    // 主题颜色选择
    themeColorComboBox = new QComboBox;
    themeColorComboBox->addItem(tr("深色"));
    themeColorComboBox->addItem(tr("浅色"));
    themeColorComboBox->setView(new QListView);

    formLayout->addRow(tr("选择主题："), themeColorComboBox);

    return widget;
}

QWidget* OptionsDlg::CreateMultilingualWidget()
{
    QWidget* multilingualWidget = new QWidget;
    QGridLayout* gridLayout     = new QGridLayout(multilingualWidget);
    gridLayout->setVerticalSpacing(21);

    QLabel* multiLanguageLabel = new QLabel(tr("多语言"), multilingualWidget);
    multiLanguageLabel->setObjectName("multilingual_Label");

    QLabel* selectLanguageLabel = new QLabel(tr("选择语言："), multilingualWidget);
    selectLanguageLabel->setObjectName("select_Language_Label");

    languageComboBox = new QComboBox(multilingualWidget);
    languageComboBox->setObjectName("select_Language_ComboBox");
    languageComboBox->addItem(tr("中文"));
    languageComboBox->addItem(tr("英文"));
    languageComboBox->setView(new QListView);

    QSpacerItem* horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QSpacerItem* verticalSpacer   = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);

    gridLayout->addWidget(multiLanguageLabel, 0, 0);
    gridLayout->addWidget(selectLanguageLabel, 1, 0);
    gridLayout->addWidget(languageComboBox, 1, 1);
    gridLayout->addItem(horizontalSpacer, 1, 2, 1, 1);
    gridLayout->addItem(verticalSpacer, 2, 0, 1, 1);

    return multilingualWidget;
}

QWidget* OptionsDlg::CreateCADEnvironmentSettingsWidget()
{
    QWidget* widget                        = new QWidget;
    QVBoxLayout* environmentSettingsLayout = new QVBoxLayout(widget);
    environmentSettingsLayout->setContentsMargins(0, 0, 0, 0);
    environmentSettingsLayout->addWidget(CreateColorSettingWidget());
    environmentSettingsLayout->addWidget(CreateModeAndLightingSettingWidget());
    environmentSettingsLayout->addWidget(SketchDrawingAndModeAxiseSettingWidget());
    environmentSettingsLayout->addStretch();
    return widget;
}

QWidget* OptionsDlg::CreateColorSettingWidget()
{
    QWidget* widget = new QWidget;
    widget->setObjectName("colorSetting_Widget");
    QVBoxLayout* colorSettingWidgetVLayout = new QVBoxLayout(widget);
    QWidget* colorSettingTitleWidget       = new QWidget;
    colorSettingTitleWidget->setFixedHeight(15);

    QWidget* backgroundColorSettingWidget = new QWidget;
    colorSettingWidgetVLayout->addWidget(colorSettingTitleWidget);
    colorSettingWidgetVLayout->addSpacing(10);
    colorSettingWidgetVLayout->addWidget(backgroundColorSettingWidget);

    QHBoxLayout* colorTitleHLayout = new QHBoxLayout(colorSettingTitleWidget);
    colorTitleHLayout->setContentsMargins(0, 0, 0, 0);
    QLabel* environmentSettingLabel = new QLabel;
    environmentSettingLabel->setObjectName("colorTitle_Label");
    environmentSettingLabel->setText("颜色");
    colorTitleHLayout->addWidget(environmentSettingLabel);
    colorTitleHLayout->addStretch();

    QHBoxLayout* backgroundColorHLayout = new QHBoxLayout(backgroundColorSettingWidget);
    backgroundColorHLayout->setContentsMargins(0, 0, 0, 0);
    QLabel* backgroundColorLabel = new QLabel;
    backgroundColorLabel->setObjectName("backgroundColor_Label");
    backgroundColorLabel->setText("背景渐变色：");

    QLabel* backgroundColorPreviewLabel = new QLabel;
    backgroundColorPreviewLabel->setObjectName("backgroundColorPreview_Label");
    backgroundColorPreviewLabel->setText("预览");

    backgroundColorHLayout->addWidget(backgroundColorLabel);
    backgroundColorHLayout->addSpacing(10);
    backgroundColorHLayout->addWidget(topColorBtn);
    backgroundColorHLayout->addSpacing(8);
    backgroundColorHLayout->addWidget(bottomColorBtn);
    backgroundColorHLayout->addStretch();
    backgroundColorHLayout->addWidget(backgroundColorPreviewLabel);
    backgroundColorHLayout->addWidget(backgroundGradientColorLabel);
    backgroundColorHLayout->addSpacing(40);
    return widget;
}

QWidget* OptionsDlg::CreateModeAndLightingSettingWidget()
{
    /// 模型预览区域
    QWidget* widget                      = new QWidget;
    QWidget* demonstrationModelWidget    = new QWidget;
    QVBoxLayout* modelColorPreviewLayout = new QVBoxLayout(demonstrationModelWidget);
    modelColorPreviewLayout->setContentsMargins(0, 0, 0, 0);

    modelColorPreviewWidget = new ModelColorPreviewWidget;
    modelColorPreviewWidget->setObjectName("modelColorPreviewWidget");
    modelColorPreviewLayout->addWidget(modelColorPreviewWidget);

    QLabel* modeTitleLabel = new QLabel;
    modeTitleLabel->setObjectName("modeTitle_Label");
    modeTitleLabel->setText("模型");
    QHBoxLayout* modeColorTitleHLayout = new QHBoxLayout;
    modeColorTitleHLayout->addWidget(modeTitleLabel);
    modeColorTitleHLayout->addStretch();

    QLabel* faceColorLabel = new QLabel;
    faceColorLabel->setObjectName("modeColor_Label");
    faceColorLabel->setText("面：");

    QLabel* edgeColorLabel = new QLabel;
    edgeColorLabel->setObjectName("modeColor_Label");
    edgeColorLabel->setText("线：");

    QLabel* vertexColorLabel = new QLabel;
    vertexColorLabel->setObjectName("modeColor_Label");
    vertexColorLabel->setText("点：");

    QHBoxLayout* modeColorHLayout = new QHBoxLayout;
    modeColorHLayout->addWidget(faceColorLabel);
    modeColorHLayout->addSpacing(12);
    modeColorHLayout->addWidget(faceColorBtn);
    modeColorHLayout->addSpacing(15);
    modeColorHLayout->addWidget(edgeColorLabel);
    modeColorHLayout->addSpacing(12);
    modeColorHLayout->addWidget(edgeColorBtn);
    modeColorHLayout->addSpacing(15);
    modeColorHLayout->addWidget(vertexColorLabel);
    modeColorHLayout->addSpacing(12);
    modeColorHLayout->addWidget(vertexColorBtn);
    modeColorHLayout->addStretch();

    QLabel* lightingTitleLabel = new QLabel;
    lightingTitleLabel->setObjectName("LightingTitle_Label");
    lightingTitleLabel->setText("灯光");
    QHBoxLayout* LightingTitleHLayout = new QHBoxLayout;
    LightingTitleHLayout->addWidget(lightingTitleLabel);
    LightingTitleHLayout->addStretch();


    QLabel* highlightColorLabel = new QLabel;
    highlightColorLabel->setObjectName("LightingColor_Label");
    highlightColorLabel->setText("选中后高亮：");

    QHBoxLayout* lightingHLayout = new QHBoxLayout;
    lightingHLayout->addWidget(highlightColorLabel);
    lightingHLayout->addWidget(highLightColorBtn);
    lightingHLayout->addStretch();

    QVBoxLayout* modeSettingVLayout = new QVBoxLayout;
    modeSettingVLayout->addLayout(modeColorTitleHLayout);
    modeSettingVLayout->addSpacing(10);
    modeSettingVLayout->addLayout(modeColorHLayout);
    modeSettingVLayout->addSpacing(15);
    modeSettingVLayout->addLayout(LightingTitleHLayout);
    modeSettingVLayout->addSpacing(10);
    modeSettingVLayout->addLayout(lightingHLayout);

    QHBoxLayout* modeSettingHLayout = new QHBoxLayout(widget);
    modeSettingHLayout->addLayout(modeSettingVLayout);
    modeSettingHLayout->addSpacing(50);
    modeSettingHLayout->addWidget(demonstrationModelWidget);
    modeSettingHLayout->addSpacing(30);
    return widget;
}

QWidget* OptionsDlg::SketchDrawingAndModeAxiseSettingWidget()
{
    QWidget* widget              = new QWidget;
    QWidget* sketchDrawingWidget = new QWidget;
    {
        QVBoxLayout* sketchDrawingVLayout = new QVBoxLayout(sketchDrawingWidget);
        sketchDrawingVLayout->setContentsMargins(0, 0, 0, 0);

        QWidget* sketchDrawingTitleWidget = new QWidget;
        sketchDrawingTitleWidget->setFixedHeight(30);
        QHBoxLayout* sketchDrawingTitleHLayout = new QHBoxLayout(sketchDrawingTitleWidget);
        sketchDrawingTitleHLayout->setContentsMargins(0, 0, 0, 0);

        QLabel* sketchDrawingTitleLabel = new QLabel;
        sketchDrawingTitleLabel->setObjectName("sketchDrawingTitle_Label");
        sketchDrawingTitleLabel->setText("草图绘制");
        sketchDrawingTitleHLayout->addWidget(sketchDrawingTitleLabel);
        sketchDrawingTitleHLayout->addStretch();

        QWidget* sketchDrawingSettingWidget      = new QWidget;
        QHBoxLayout* sketchDrawingSettingHLayout = new QHBoxLayout(sketchDrawingSettingWidget);
        sketchDrawingSettingHLayout->setContentsMargins(0, 0, 0, 0);
        QLabel* sketchLineSegmentsColorLabel = new QLabel;
        sketchLineSegmentsColorLabel->setObjectName("sketchDrawingColor_Label");
        sketchLineSegmentsColorLabel->setText("草图绘制线段：");

        QLabel* sketchDimensionLinesColorLabel = new QLabel;
        sketchDimensionLinesColorLabel->setObjectName("sketchDrawingColor_Label");
        sketchDimensionLinesColorLabel->setText("草图尺寸线：");

        QLabel* gridLineColorLabel = new QLabel;
        gridLineColorLabel->setObjectName("sketchDrawingColor_Label");
        gridLineColorLabel->setText("网格线：");

        sketchDrawingSettingHLayout->addWidget(sketchLineSegmentsColorLabel);
        sketchDrawingSettingHLayout->addWidget(lineSegmentColorBtn);
        sketchDrawingSettingHLayout->addSpacing(20);
        sketchDrawingSettingHLayout->addWidget(sketchDimensionLinesColorLabel);
        sketchDrawingSettingHLayout->addWidget(dimensionLineColorBtn);
        sketchDrawingSettingHLayout->addSpacing(20);
        sketchDrawingSettingHLayout->addWidget(gridLineColorLabel);
        sketchDrawingSettingHLayout->addWidget(gridLineColorBtn);
        sketchDrawingSettingHLayout->addStretch();

        sketchDrawingVLayout->addWidget(sketchDrawingTitleWidget);
        sketchDrawingVLayout->addWidget(sketchDrawingSettingWidget);
    }

    QHBoxLayout* renderHlayout = new QHBoxLayout;
    {
        QLabel* renderSettingLab = new QLabel(QStringLiteral("渲染设置"));
        renderSettingLab->setObjectName(QStringLiteral("renderSetting_Lab"));

        QLabel* modelLineSettingLab = new QLabel(QStringLiteral("模型线设置"));
        modelLineSettingLab->setObjectName(QStringLiteral("modelLineSetting_Lab"));

        QLabel* modelLineTypeLab = new QLabel(QStringLiteral("线型："));
        modelLineTypeLab->setObjectName(QStringLiteral("modelLineType_Lab"));

        lineTypeComBox = new QComboBox;
        lineTypeComBox->setObjectName(QStringLiteral("lineType_ComBox"));

        QStringList items;
        items << "实线" << "点线" << "点划线" << "中心线" << "虚线" << "双点线" << "三点线";
        lineTypeComBox->addItems(items);

        LineTypeDelegate* delegate = new LineTypeDelegate(lineTypeComBox);
        lineTypeComBox->setItemDelegate(delegate);

        QLabel* modelLineWidthLab = new QLabel(QStringLiteral("线宽："));
        modelLineWidthLab->setObjectName(QStringLiteral("modelLineWidth_Lab"));

        lineWidthLineEdit = new QLineEdit;
        lineWidthLineEdit->setFixedSize(70, 23);

        QLabel* modelFaceSettingLab = new QLabel(QStringLiteral("背面颜色设置"));
        modelFaceSettingLab->setObjectName(QStringLiteral("modelFaceSetting_Lab"));

        modelFaceCheckBox = new QCheckBox(QStringLiteral("启用设置"));
        modelFaceCheckBox->setObjectName(QStringLiteral("modelFace_CheckBox"));
        modelFaceCheckBox->setFixedSize(75, 25);

        QLabel* modelBackFaceColorSettingLab = new QLabel(QStringLiteral("背面颜色："));
        modelBackFaceColorSettingLab->setObjectName(QStringLiteral("modelBackFaceColorSetting_Lab"));

        QLabel* highlightContourSettingLab = new QLabel(QStringLiteral("高亮轮廓设置"));
        highlightContourSettingLab->setObjectName(QStringLiteral("HighlightContourSetting_Lab"));

        highlightContourCheckBox = new QCheckBox(QStringLiteral("启用设置"));
        highlightContourCheckBox->setObjectName(QStringLiteral("highlightContour_CheckBox"));
        highlightContourCheckBox->setFixedSize(75, 25);

        QLabel* highlightContourColorLab = new QLabel(QStringLiteral("轮廓颜色："));
        highlightContourColorLab->setObjectName(QStringLiteral("HighlightContourColor_Lab"));

        QLabel* displayFrameRateLab = new QLabel(QStringLiteral("帧率显示"));
        displayFrameRateLab->setObjectName(QStringLiteral("DisplayFrameRate_Lab"));

        displayFrameRateButton = new QRadioButton(QStringLiteral("显示"));
        displayFrameRateButton->setObjectName(QStringLiteral("displayFrameRate_Button"));
        displayFrameRateButton->setFixedSize(65, 25);

        hideFrameRateButton = new QRadioButton(QStringLiteral("不显示"));
        hideFrameRateButton->setObjectName(QStringLiteral("hideFrameRate_Button"));
        hideFrameRateButton->setFixedSize(65, 25);

        QGridLayout* renderSettingsGLayout = new QGridLayout;
        renderSettingsGLayout->setContentsMargins(0, 0, 0, 0);
        renderSettingsGLayout->setHorizontalSpacing(20);
        renderSettingsGLayout->setVerticalSpacing(5);

        renderSettingsGLayout->addWidget(renderSettingLab, 0, 0);
        renderSettingsGLayout->addWidget(modelLineSettingLab, 1, 0);
        renderSettingsGLayout->addWidget(modelLineTypeLab, 1, 1);
        renderSettingsGLayout->addWidget(lineTypeComBox, 1, 2);
        renderSettingsGLayout->addWidget(modelLineWidthLab, 1, 3);
        renderSettingsGLayout->addWidget(lineWidthLineEdit, 1, 4);
        renderSettingsGLayout->addWidget(modelFaceSettingLab, 2, 0);
        renderSettingsGLayout->addWidget(modelFaceCheckBox, 2, 1);
        renderSettingsGLayout->addWidget(modelBackFaceColorSettingLab, 2, 2);
        renderSettingsGLayout->addWidget(backFaceColorSettingBtn, 2, 3);
        renderSettingsGLayout->addWidget(highlightContourSettingLab, 3, 0);
        renderSettingsGLayout->addWidget(highlightContourCheckBox, 3, 1);
        renderSettingsGLayout->addWidget(highlightContourColorLab, 3, 2);
        renderSettingsGLayout->addWidget(highlightContourColorSettingBtn, 3, 3);
        renderSettingsGLayout->addWidget(displayFrameRateLab, 4, 0);

        QWidget* radioFrameRateWidget = new QWidget(widget);
        QHBoxLayout* frameRateHlayout = new QHBoxLayout(radioFrameRateWidget);
        frameRateHlayout->setContentsMargins(0, 0, 0, 0);
        frameRateHlayout->addWidget(displayFrameRateButton);
        frameRateHlayout->addSpacing(5);
        frameRateHlayout->addWidget(hideFrameRateButton);
        frameRateHlayout->addStretch();
        renderSettingsGLayout->addWidget(radioFrameRateWidget, 4, 1, 1, 2);

        renderHlayout->addLayout(renderSettingsGLayout);
        renderHlayout->addStretch();
    }

    QWidget* objectDisplayWidget = new QWidget;
    {
        QHBoxLayout* showHLayout = new QHBoxLayout(objectDisplayWidget);
        showHLayout->setContentsMargins(0, 0, 0, 0);
        QLabel* objectDisplayModeLabel = new QLabel(tr("对象显示模式"));
        objectDisplayModeLabel->setObjectName("objectDisplayMode_Label");
        faceBtn   = new QPushButton;
        edgeBtn   = new QPushButton;
        vertexBtn = new QPushButton;
        faceBtn->setObjectName("face_Button");
        edgeBtn->setObjectName("edge_Button");
        vertexBtn->setObjectName("vertex_Button");
        showHLayout->addWidget(objectDisplayModeLabel);
        showHLayout->addSpacing(13);
        showHLayout->addWidget(faceBtn);
        showHLayout->addSpacing(5);
        showHLayout->addWidget(edgeBtn);
        showHLayout->addSpacing(5);
        showHLayout->addWidget(vertexBtn);
        showHLayout->addStretch();

        faceBtn->setCheckable(true);
        faceBtn->setChecked(true);
        edgeBtn->setCheckable(true);
        edgeBtn->setChecked(true);
        vertexBtn->setCheckable(true);
        vertexBtn->setChecked(true);

        faceIconLabel   = new QLabel(faceBtn);
        edgeIconLabel   = new QLabel(edgeBtn);
        vertexIconLabel = new QLabel(vertexBtn);

        QLabel* faceTextLabel = new QLabel(faceBtn);
        faceTextLabel->setText(tr("面"));
        faceTextLabel->setObjectName("DisplayMode_Label");

        QLabel* edgeTextLabel = new QLabel(edgeBtn);
        edgeTextLabel->setText(tr("线"));
        edgeTextLabel->setObjectName("DisplayMode_Label");

        QLabel* vertexTextLabel = new QLabel(vertexBtn);
        vertexTextLabel->setText(tr("点"));
        vertexTextLabel->setObjectName("DisplayMode_Label");

        QHBoxLayout* faceButtonLayout   = new QHBoxLayout(faceBtn);
        QHBoxLayout* edgeButtonLayout   = new QHBoxLayout(edgeBtn);
        QHBoxLayout* vertexButtonLayout = new QHBoxLayout(vertexBtn);
        faceButtonLayout->setContentsMargins(0, 0, 0, 0);
        edgeButtonLayout->setContentsMargins(0, 0, 0, 0);
        vertexButtonLayout->setContentsMargins(0, 0, 0, 0);
        updateDisplayModeIcon();

        faceButtonLayout->addWidget(faceIconLabel);
        faceButtonLayout->addWidget(faceTextLabel);
        edgeButtonLayout->addWidget(edgeIconLabel);
        edgeButtonLayout->addWidget(edgeTextLabel);
        vertexButtonLayout->addWidget(vertexIconLabel);
        vertexButtonLayout->addWidget(vertexTextLabel);
    }

    QWidget* axiseDisplayWidget = new QWidget;
    {
        QHBoxLayout* hBoxLayout = new QHBoxLayout(axiseDisplayWidget);
        hBoxLayout->setContentsMargins(0, 0, 0, 0);
        QLabel* labelTitle = new QLabel(tr("操作轴"));
        labelTitle->setObjectName("operatingAxise_Label");
        displayOperatingAxiseBtn = new QRadioButton;
        displayOperatingAxiseBtn->setObjectName("displayOperatingAxise_Button");
        displayOperatingAxiseBtn->setText(tr("显示"));
        displayOperatingAxiseBtn->setFixedSize(65, 25);
        displayOperatingAxiseBtn->setChecked(true);

        hideOperatingAxiseBtn = new QRadioButton;
        hideOperatingAxiseBtn->setObjectName("hideOperatingAxise_Button");
        hideOperatingAxiseBtn->setText(tr("隐藏"));
        hideOperatingAxiseBtn->setFixedSize(65, 25);

        QButtonGroup* buttonGroup = new QButtonGroup(axiseDisplayWidget);
        buttonGroup->addButton(displayOperatingAxiseBtn);
        buttonGroup->addButton(hideOperatingAxiseBtn);

        hBoxLayout->addWidget(labelTitle);
        hBoxLayout->addSpacing(55);
        hBoxLayout->addWidget(displayOperatingAxiseBtn);
        hBoxLayout->addSpacing(5);
        hBoxLayout->addWidget(hideOperatingAxiseBtn);
        hBoxLayout->addStretch();
    }

    QWidget* highlightWidget = new QWidget;
    {
        QHBoxLayout* hBoxLayout = new QHBoxLayout(highlightWidget);
        hBoxLayout->setContentsMargins(0, 0, 0, 0);
        QLabel* labelTitle = new QLabel(tr("实时高亮"));
        labelTitle->setObjectName("operatingAxise_Label");
        highlightBtn = new QRadioButton;
        highlightBtn->setObjectName("displayOperatingAxise_Button");
        highlightBtn->setText(tr("是"));
        highlightBtn->setFixedSize(65, 25);
        highlightBtn->setChecked(true);

        hideHighlightBtn = new QRadioButton;
        hideHighlightBtn->setObjectName("hideOperatingAxise_Button");
        hideHighlightBtn->setText(tr("否"));
        hideHighlightBtn->setFixedSize(65, 25);

        QButtonGroup* buttonGroup = new QButtonGroup(highlightWidget);
        buttonGroup->addButton(highlightBtn);
        buttonGroup->addButton(hideHighlightBtn);

        hBoxLayout->addWidget(labelTitle);
        hBoxLayout->addSpacing(40);
        hBoxLayout->addWidget(highlightBtn);
        hBoxLayout->addSpacing(5);
        hBoxLayout->addWidget(hideHighlightBtn);
        hBoxLayout->addStretch();
    }

    QWidget* selectAllWidget = new QWidget;
    {
        QHBoxLayout* hBoxLayout = new QHBoxLayout(selectAllWidget);
        hBoxLayout->setContentsMargins(0, 0, 0, 0);
        QLabel* labelTitle = new QLabel(tr("框选所有"));
        labelTitle->setObjectName("operatingAxise_Label");
        selectAllBtn = new QRadioButton;
        selectAllBtn->setObjectName("displayOperatingAxise_Button");
        selectAllBtn->setText(tr("是"));
        selectAllBtn->setFixedSize(65, 25);

        hideSelectAllBtn = new QRadioButton;
        hideSelectAllBtn->setObjectName("hideOperatingAxise_Button");
        hideSelectAllBtn->setText(tr("否"));
        hideSelectAllBtn->setFixedSize(65, 25);
        hideSelectAllBtn->setChecked(true);

        QButtonGroup* axisButtonGroup = new QButtonGroup(selectAllWidget);
        axisButtonGroup->addButton(selectAllBtn);
        axisButtonGroup->addButton(hideSelectAllBtn);

        hBoxLayout->addWidget(labelTitle);
        hBoxLayout->addSpacing(40);
        hBoxLayout->addWidget(selectAllBtn);
        hBoxLayout->addSpacing(5);
        hBoxLayout->addWidget(hideSelectAllBtn);
        hBoxLayout->addStretch();
    }

    QVBoxLayout* sketchDrawingAndModeAxiseVLayout = new QVBoxLayout(widget);
    sketchDrawingAndModeAxiseVLayout->addWidget(sketchDrawingWidget);
    sketchDrawingAndModeAxiseVLayout->addSpacing(15);
    sketchDrawingAndModeAxiseVLayout->addLayout(renderHlayout);
    sketchDrawingAndModeAxiseVLayout->addSpacing(15);
    sketchDrawingAndModeAxiseVLayout->addWidget(objectDisplayWidget);
    sketchDrawingAndModeAxiseVLayout->addSpacing(15);
    sketchDrawingAndModeAxiseVLayout->addWidget(axiseDisplayWidget);
    sketchDrawingAndModeAxiseVLayout->addSpacing(15);
    sketchDrawingAndModeAxiseVLayout->addWidget(highlightWidget);
    sketchDrawingAndModeAxiseVLayout->addSpacing(15);
    sketchDrawingAndModeAxiseVLayout->addWidget(selectAllWidget);
    
    sketchDrawingAndModeAxiseVLayout->addSpacing(15);
    return widget;
}

QWidget* OptionsDlg::CreatePathSettingsWidget11()
{
    QWidget* widget         = new QWidget();
    QVBoxLayout* vBoxLayout = new QVBoxLayout(widget);
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setVerticalSpacing(22);
    vBoxLayout->addLayout(gridLayout);
    vBoxLayout->addStretch();

    QLabel* testCasePathLabel = new QLabel(tr("测试用例模型路径"), widget);
    testCasePathLabel->setObjectName("testCaseModePath_Label");

    QLabel* selectTestCasePathLabel = new QLabel(tr("路径选择："), widget);
    selectTestCasePathLabel->setObjectName("PathSelect_Label");
    selectTestCasePathLabel->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignTop);

    testCasePathListWidget = new QListWidget(widget);
    testCasePathListWidget->setObjectName("testCasePath_ListWidget");
    testCasePathListWidget->setFixedHeight(150);

    QWidget* actionWidget = new QWidget(widget);
    actionWidget->setFixedHeight(150);
    addTestCasePathBtn = new QPushButton(tr("新增"), actionWidget);
    addTestCasePathBtn->setObjectName("browseButton_addTestCasePath");
    addTestCasePathBtn->setIcon(QIcon(":/Option/add.png"));
    addTestCasePathBtn->setFixedSize(65, 25);

    deleteTestCasePathBtn = new QPushButton(tr("删除"), actionWidget);
    deleteTestCasePathBtn->setObjectName("browseButton_deleteTestCasePath");
    deleteTestCasePathBtn->setIcon(QIcon(":/Option/delete.png"));
    deleteTestCasePathBtn->setFixedSize(65, 25);

    QVBoxLayout* actionLayout = new QVBoxLayout(actionWidget);
    actionLayout->setContentsMargins(6, 0, 6, 6);
    actionLayout->addWidget(addTestCasePathBtn);
    actionLayout->addWidget(deleteTestCasePathBtn);
    actionLayout->addStretch();

    QLabel* pythonScriptLabel = new QLabel(tr("Python脚本路径"), widget);
    pythonScriptLabel->setObjectName("pythonScriptPath_Label");

    QLabel* selectPythonScriptPathLabel = new QLabel(tr("路径选择："), widget);
    selectPythonScriptPathLabel->setObjectName("PathSelect_Label");

    pythonScriptPathLineEdit = new QLineEdit(widget);
    pythonScriptPathLineEdit->setObjectName("pythonScriptPath_LineEdit");
    pythonScriptPathLineEdit->setReadOnly(true);

    pythonScriptPathButton = new QPushButton(tr("浏览"), widget);
    pythonScriptPathButton->setObjectName("browseButton_pythonScriptPath");
    pythonScriptPathButton->setFixedSize(65, 25);

    QLabel* pythonPathLabel = new QLabel(tr("Python路径"), widget);
    pythonPathLabel->setObjectName("pythonPath_Label");

    QLabel* selectPythonPathLabel = new QLabel(tr("路径选择："), widget);
    selectPythonPathLabel->setObjectName("PathSelect_Label");

    pythonPathLineEdit = new QLineEdit(widget);
    pythonPathLineEdit->setObjectName("pythonPath_LineEdit");
    pythonPathLineEdit->setReadOnly(true);

    pythonPathButton = new QPushButton(tr("浏览"), widget);
    pythonPathButton->setObjectName("browseButton_pythonPath");
    pythonPathButton->setFixedSize(65, 25);

    gridLayout->addWidget(testCasePathLabel, 0, 0, 1, 2);
    gridLayout->addWidget(selectTestCasePathLabel, 1, 0);
    gridLayout->addWidget(testCasePathListWidget, 1, 1, Qt::AlignTop);
    gridLayout->addWidget(actionWidget, 1, 2);
    gridLayout->addWidget(pythonScriptLabel, 2, 0, 1, 2);
    gridLayout->addWidget(selectPythonScriptPathLabel, 3, 0);
    gridLayout->addWidget(pythonScriptPathLineEdit, 3, 1);
    gridLayout->addWidget(pythonScriptPathButton, 3, 2);
    gridLayout->addWidget(pythonPathLabel, 4, 0, 1, 2);
    gridLayout->addWidget(selectPythonPathLabel, 5, 0);
    gridLayout->addWidget(pythonPathLineEdit, 5, 1);
    gridLayout->addWidget(pythonPathButton, 5, 2);

    return widget;
}

QWidget* OptionsDlg::CreatePathSettingsWidget()
{
    QWidget* widget = new QWidget();
    QVBoxLayout* mainLayout = new QVBoxLayout(widget);

    // 测试用例路径设置
    QGroupBox* testCaseGroup = new QGroupBox(tr("测试用例模型路径"));
    QVBoxLayout* testCaseLayout = new QVBoxLayout(testCaseGroup);

    testCasePathListWidget = new QListWidget;
    testCasePathListWidget->setFixedHeight(150);

    QHBoxLayout* testCaseButtonLayout = new QHBoxLayout;
    addTestCasePathBtn = new QPushButton(tr("新增"));
    addTestCasePathBtn->setObjectName("browseButton_addTestCasePath");
    addTestCasePathBtn->setIcon(QIcon(":/Option/add.png"));
    deleteTestCasePathBtn = new QPushButton(tr("删除"));
    deleteTestCasePathBtn->setObjectName("browseButton_deleteTestCasePath");
    deleteTestCasePathBtn->setIcon(QIcon(":/Option/delete.png"));
    testCaseButtonLayout->addWidget(addTestCasePathBtn);
    testCaseButtonLayout->addWidget(deleteTestCasePathBtn);
    testCaseButtonLayout->addStretch();

    testCaseLayout->addWidget(testCasePathListWidget);
    testCaseLayout->addLayout(testCaseButtonLayout);

    // Python 脚本路径设置
    QGroupBox* pythonGroup = new QGroupBox(tr("Python 脚本设置"));
    QFormLayout* pythonLayout = new QFormLayout(pythonGroup);

    pythonScriptPathLineEdit = new QLineEdit;
    pythonScriptPathLineEdit->setReadOnly(true);
    pythonScriptPathButton = new QPushButton(tr("浏览"));
    pythonScriptPathButton->setObjectName("browseButton_pythonScriptPath");
    QHBoxLayout* scriptPathLayout = new QHBoxLayout;
    scriptPathLayout->addWidget(pythonScriptPathLineEdit);
    scriptPathLayout->addWidget(pythonScriptPathButton);
    pythonLayout->addRow(tr("脚本路径："), scriptPathLayout);

    pythonPathLineEdit = new QLineEdit;
    pythonPathLineEdit->setReadOnly(true);
    pythonPathButton = new QPushButton(tr("浏览"));
    pythonPathButton->setObjectName("browseButton_pythonPath");
    QHBoxLayout* pythonPathLayout = new QHBoxLayout;
    pythonPathLayout->addWidget(pythonPathLineEdit);
    pythonPathLayout->addWidget(pythonPathButton);
    pythonLayout->addRow(tr("Python 路径："), pythonPathLayout);

    mainLayout->addWidget(testCaseGroup);
    mainLayout->addWidget(pythonGroup);
    mainLayout->addStretch();

    return widget;
}

QWidget* OptionsDlg::CreateLoadingPluginsWidget()
{
    QWidget* widget         = new QWidget();
    QVBoxLayout* vBoxLayout = new QVBoxLayout(widget);
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setVerticalSpacing(21);
    vBoxLayout->addLayout(gridLayout);

    QLabel* loadingPluginsLabel = new QLabel(tr("加载插件"), widget);
    loadingPluginsLabel->setObjectName("loadingPlugins_Label");

    treeWidget = new QTreeWidget(widget);
    treeWidget->setObjectName("tree_Widget");
    treeWidget->setColumnCount(1);
    treeWidget->setHeaderLabel("插件");
    treeWidget->header()->hide();

    QWidget* actionWidget         = new QWidget(widget);
    QVBoxLayout* vBoxActionLayout = new QVBoxLayout(actionWidget);
    vBoxActionLayout->setContentsMargins(6, 0, 6, 6);
    
    addLoadingPluginBtn    = new QPushButton(tr("新增"), widget);
    addLoadingPluginBtn->setObjectName("browseButton_addLoadingPlugins");
    addLoadingPluginBtn->setIcon(QIcon(":/Option/add.png"));
    addLoadingPluginBtn->setFixedSize(65, 25);

    deleteLoadingPluginBtn = new QPushButton(tr("删除"), widget);
    deleteLoadingPluginBtn->setObjectName("browseButton_deleteLoadingPlugins");
    deleteLoadingPluginBtn->setIcon(QIcon(":/Option/delete.png"));
    deleteLoadingPluginBtn->setFixedSize(65, 25);

    vBoxActionLayout->addWidget(addLoadingPluginBtn);
    vBoxActionLayout->addWidget(deleteLoadingPluginBtn);
    vBoxActionLayout->addStretch();

    gridLayout->addWidget(loadingPluginsLabel, 0, 0);
    gridLayout->addWidget(treeWidget, 1, 0);
    gridLayout->addWidget(actionWidget, 1, 1);

    return widget;
}

QWidget* OptionsDlg::CreateWindowWidget()
{
    QWidget* widget         = new QWidget();
    QVBoxLayout* vBoxLayout = new QVBoxLayout(widget);
    vBoxLayout->setContentsMargins(0, 0, 0, 0);
    QHBoxLayout* consoleTitleHLayout           = new QHBoxLayout;
    QWidget* consoleShowOrHideWidget           = new QWidget(widget);
    QHBoxLayout* consoleShowOrHideHLayout      = new QHBoxLayout(consoleShowOrHideWidget);
    QHBoxLayout* scriptEditorTitleHLayout      = new QHBoxLayout;
    QWidget* scriptEditorShowOrHideWidget      = new QWidget(widget);
    QHBoxLayout* scriptEditorShowOrHideHLayout = new QHBoxLayout(scriptEditorShowOrHideWidget);
    vBoxLayout->addSpacing(7);
    vBoxLayout->addLayout(consoleTitleHLayout);
    vBoxLayout->addWidget(consoleShowOrHideWidget);
    vBoxLayout->addLayout(scriptEditorTitleHLayout);
    vBoxLayout->addWidget(scriptEditorShowOrHideWidget);
    vBoxLayout->addStretch();

    QLabel* consoleLabel = new QLabel(tr("控制台"), widget);
    consoleLabel->setObjectName("console_Label");
    consoleLabel->resize(100, 30);
    consoleTitleHLayout->addSpacing(8);
    consoleTitleHLayout->addWidget(consoleLabel);
    consoleTitleHLayout->addStretch();

    displayConsoleButton = new QRadioButton(consoleShowOrHideWidget);
    displayConsoleButton->setText(tr("显示"));
    displayConsoleButton->setFixedSize(60, 30);
    hideConsoleButton = new QRadioButton(consoleShowOrHideWidget);
    hideConsoleButton->setText(tr("隐藏"));
    hideConsoleButton->setFixedSize(60, 30);
    consoleShowOrHideHLayout->addWidget(displayConsoleButton);
    consoleShowOrHideHLayout->addWidget(hideConsoleButton);
    consoleShowOrHideHLayout->addStretch();

    QLabel* scriptEditorLabel = new QLabel(tr("脚本编辑器"), widget);
    scriptEditorLabel->setObjectName("scriptEditor_Label");
    scriptEditorLabel->resize(100, 30);
    scriptEditorTitleHLayout->addSpacing(8);
    scriptEditorTitleHLayout->addWidget(scriptEditorLabel);
    scriptEditorTitleHLayout->addStretch();

    displayScriptEditorButton = new QRadioButton(scriptEditorShowOrHideWidget);
    displayScriptEditorButton->setText(tr("显示"));
    displayScriptEditorButton->setFixedSize(60, 30);
    hideScriptEditorButton = new QRadioButton(scriptEditorShowOrHideWidget);
    hideScriptEditorButton->setText(tr("隐藏"));
    hideScriptEditorButton->setFixedSize(60, 30);
    scriptEditorShowOrHideHLayout->addWidget(displayScriptEditorButton);
    scriptEditorShowOrHideHLayout->addWidget(hideScriptEditorButton);
    scriptEditorShowOrHideHLayout->addStretch();

    return widget;
}

QWidget* OptionsDlg::CreateBackupsWidget()
{
    QWidget* backupsWidget     = new QWidget();
    QVBoxLayout* backupsLayout = new QVBoxLayout(backupsWidget);
    backupsLayout->setContentsMargins(0, 0, 0, 0);
    QWidget* openOrCloseBackupsWidget         = new QWidget(backupsWidget);
    QHBoxLayout* openOrCloseBackupsHLayout    = new QHBoxLayout(openOrCloseBackupsWidget);
    QHBoxLayout* backupIntervalTitleHLayout   = new QHBoxLayout;
    QHBoxLayout* backupIntervalSettingHLayout = new QHBoxLayout;
    QHBoxLayout* backupPathHLayout            = new QHBoxLayout;
    QHBoxLayout* backupPathSelectHLayout      = new QHBoxLayout;
    backupsLayout->addWidget(openOrCloseBackupsWidget);
    backupsLayout->addLayout(backupIntervalTitleHLayout);
    backupsLayout->addLayout(backupIntervalSettingHLayout);
    backupsLayout->addLayout(backupPathHLayout);
    backupsLayout->addLayout(backupPathSelectHLayout);
    backupsLayout->addStretch();

    QLabel* backupsLabel = new QLabel(tr("是否开启备份："), openOrCloseBackupsWidget);
    backupsLabel->setObjectName("openOrCloseBackups_Label");
    backupsLabel->resize(100, 30);
    openBackupsButton = new QRadioButton(openOrCloseBackupsWidget);
    openBackupsButton->setObjectName("openBackups_Button");
    openBackupsButton->setText(tr("开启"));
    openBackupsButton->setFixedSize(60, 30);
    closeBackupsButton = new QRadioButton(openOrCloseBackupsWidget);
    closeBackupsButton->setObjectName("closeBackups_Button");
    closeBackupsButton->setText(tr("不开启"));
    closeBackupsButton->setFixedSize(70, 30);
    openOrCloseBackupsHLayout->addWidget(backupsLabel);
    openOrCloseBackupsHLayout->addWidget(openBackupsButton);
    openOrCloseBackupsHLayout->addWidget(closeBackupsButton);
    openOrCloseBackupsHLayout->addStretch();

    QLabel* backupIntervalLabel = new QLabel(tr("备份时间间隔"));
    backupIntervalLabel->setObjectName("backupInterval_Label");
    backupIntervalLabel->setFixedSize(100, 40);
    backupIntervalTitleHLayout->addSpacing(8);
    backupIntervalTitleHLayout->addWidget(backupIntervalLabel);
    backupIntervalTitleHLayout->addStretch();

    timeLineEdit = new QLineEdit(backupsWidget);
    timeLineEdit->setObjectName("time_LineEdit");
    timeLineEdit->setFixedSize(50, 25);
    QLabel* timeLabel = new QLabel(backupsWidget);
    timeLabel->setObjectName("time_Label");
    timeLabel->setText(tr("分钟"));
    backupIntervalSettingHLayout->addSpacing(8);
    backupIntervalSettingHLayout->addWidget(timeLineEdit);
    backupIntervalSettingHLayout->addWidget(timeLabel);
    backupIntervalSettingHLayout->addStretch();

    QLabel* backupPathLabel = new QLabel(tr("备份路径"), backupsWidget);
    backupPathLabel->setObjectName("backupPath_Label");
    backupPathLabel->setFixedSize(100, 40);
    backupPathHLayout->addSpacing(8);
    backupPathHLayout->addWidget(backupPathLabel);
    backupPathHLayout->addStretch();

    QLabel* selectBackupPathLabel = new QLabel(tr("路径选择："), backupsWidget);
    selectBackupPathLabel->setObjectName("PathSelect_Label");
    selectBackupPathLabel->resize(100, 30);
    backupPathLineEdit = new QLineEdit(backupsWidget);
    backupPathLineEdit->setObjectName("backupPath_LineEdit");
    backupPathLineEdit->setReadOnly(true);
    backupPathBtn = new QPushButton(tr("浏览"), backupsWidget);
    backupPathBtn->setFixedSize(55, 25);
    backupPathBtn->setObjectName("browseButton_backupPath");
    backupPathSelectHLayout->addSpacing(8);
    backupPathSelectHLayout->addWidget(selectBackupPathLabel);
    backupPathSelectHLayout->addWidget(backupPathLineEdit);
    backupPathSelectHLayout->addWidget(backupPathBtn);

    return backupsWidget;
}

bool OptionsDlg::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        QPoint clickPos         = mouseEvent->globalPos();                // 获取全局坐标
        QPoint widgetPos        = colorWidget->mapToGlobal(QPoint(0, 0)); // 将ColorWidget的左上角转换为全局坐标
        QRect widgetRect        = QRect(widgetPos, colorWidget->size());  // 获取ColorWidget的全局矩形区域

        // 检查点击位置是否在ColorWidget外
        if (!widgetRect.contains(clickPos)) {
            colorWidget->hide();
        }
    }

    if (obj == modelColorPreviewWidget && event->type() == QEvent::MouseButtonPress) {
        if (colorWidgetVisible) {
            onHideSelectColorWidget();
            // 阻止事件进一步传递
            return true;
        }
    }
    return QDialog::eventFilter(obj, event);
}

} // namespace NCTI
